package com.jin.webvideo.base.spring.thymeleaf;

import com.jin.webvideo.base.LoginHandler;
import com.jin.webvideo.entity.SessionStore;
import com.jin.webvideo.entity.User;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;
/**
 * thymeleaf  permission 标签 login 属性
 */

public class LoginProcessor extends AbstractAttributeTagProcessor {
    private static final String ATTR_NAME = "login";
    private static final int precedence = 1000;
    protected LoginProcessor(final String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, precedence, true);
    }

    @Override
    protected void doProcess(ITemplateContext icontext, IProcessableElementTag iProcessableElementTag, AttributeName attributeName, String attrVal, IElementTagStructureHandler handler) {
        WebEngineContext context = (WebEngineContext)icontext;
        boolean needLogin = true;
        IEngineConfiguration config = context.getConfiguration();
        if (attrVal != null) {
            IStandardExpressionParser parser = StandardExpressions.getExpressionParser(config);
            IStandardExpression exp = parser.parseExpression(context, attrVal);
            needLogin = (boolean) exp.execute(context);
        }
        SessionStore store = LoginHandler.getSessionStore(context.getSession());
        // 未登录 但要求登录
        if (store == null) {
            if (needLogin) {
                handler.removeElement();
            }
            return;
        }
        User user = store.getUser();
        if ( (user != null) != needLogin) {
            handler.removeElement();
        }
        /*if (b) {
            handler.removeElement();
        }*/

    }
}
